// mircoApp/meituan_refund/index/index.js
var app = getApp();
let location = require("../../../mybehaviors/location/location");
var QQMapWX = require('../../../mymap/qqmap-wx-jssdk.min.js');
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
var qqmapsdk;
Page({

  behaviors: [location, skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    city_name: "全国",
    city_id: "",
    globalData: {
      navHeight: 0,
      navTop: 0,
      jnheight: 0,
      jnwidth: 0,
    },
    Height: 0,
    LastHeight: 0,

    CarouseList: [],
    category_list: [],
    button_group: [],
    active: 0,
    second_category_index: 0,
    language: "",

    cate_id: "",
    list: [],
    second_cate_id: "",
    page: 1,
    last_page: 1,
    point: {
      lat: "",
      lng: ""
    },
    keyword: "",

    options: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.options = options;
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en,
    });
    //设置导航栏
    this.initNavBar();
  },
  get_city_id(name) {
    app._postNetWork({
      url: app.getNetAddresss("plugin.meituan-group-buy.frontend.good.city"),
      data: {
        name
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        let city_id;
        for (let item in data) {
          city_id = data[item][0].id;
        }
        this.data.city_id = city_id;
        wx.setStorageSync('meituan_city_id', city_id)
        this.getCategory();
      }
    })
  },

  input_handle(e) {
    this.setData({
      keyword: e.detail.value
    });
  },
  goto_detail(e) {
    let data = e.currentTarget.dataset.item;
    wx.setStorageSync('meituanCategory', {
      'cate_id': this.data.cate_id
    })
    wx.setStorageSync("meituan_dealid", data.dealBaseInfo.dealGroupId);
    wx.navigateTo({
      url: `/mircoApp/meituan_refund/detail/detail?path=home&dealid=${data.dealBaseInfo.dealGroupId}&cate_id=${this.data.cate_id}&cityId=${this.data.city_id}&lng=${this.data.point.lng}&lat=${this.data.point.lat}`
    })
  },
  initNavBar() {
    //获取菜单按钮的布局位置信息
    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    //获取系统信息
    wx.getSystemInfo({
      success: res => {
        //状态栏的高度
        let statusBarHeight = res.statusBarHeight,
          //胶囊按钮与顶部的距离
          navTop = menuButtonObject.top,
          navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
        let globalData = {};
        globalData.navHeight = navHeight; //导航栏高度
        globalData.navTop = navTop; //胶囊按钮与顶部的距离
        globalData.jnheight = menuButtonObject.height; //胶囊的高度
        globalData.jnwidth = menuButtonObject.width; //胶囊的宽度
        this.setData({
          globalData
        })
      },
      fail(err) {
        console.log(err);
      }
    });
  },
  onChange(event) {
    this.setData({
      active: event.detail.name
    })
    this.data.cate_id = this.data.category_list[event.detail.index].id;
    this.getChildrenCategory();
  },
  chunk(arr, n) {
    var result = [];
    for (var i = 0, len = arr.length; i < len; i += n) {
      result.push(arr.slice(i, i + n));
    }
    return result;
  },
  second_category_handle(e) {
    this.setData({
      second_category_index: e.currentTarget.dataset.index
    })
    this.data.second_cate_id = e.currentTarget.dataset.id;
    this.getData();
  },

  open_dialog(e) {
    let data = e.detail;
    if (data.type == 1 || data.type == 2) {
      if (!this.data.city_id) {
        return app.tips("请先选择城市")
      }
      wx.setStorageSync('meituanCategory', {
        'cate_id': data.first_cate_id,
        'sId': data.second_cate_id
      })
      wx.navigateTo({
        url: `/mircoApp/meituan_refund/search/search?path=home&cityId=${this.data.city_id}&lat=${this.data.point.lat}&lng=${this.data.point.lng}&city=${this.data.city_name}&k=${data.keyword}`,
      })
    } else if (data.type == 3) {
      wx.navigateTo({
        url: data.mini_url
      })
    }
  },
  navBack: function () {
    wx.navigateBack()
  },
  navHome: function () {
    wx.navigateTo({
      url: '/packageI/citypickerPage/citypickerPage?plu=meituan'
    })
  },
  goto() {
    if (!this.data.city_id) {
      return app.tips("请先选择城市")
    }
    wx.setStorageSync('meituanCategory', {
      'cate_id': this.data.cate_id,
      'sId': this.data.second_cate_id
    })
    wx.navigateTo({
      url: `/mircoApp/meituan_refund/search/search?path=home&cityId=${this.data.city_id}&lat=${this.data.point.lat}&lng=${this.data.point.lng}&city=${this.data.city_name}&k=${this.data.keyword}`,
    })
  },
  imgHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    if (e && e.detail) {
      var imgh = e.detail.height; //图片高度
      var imgw = e.detail.width; //图片宽度
      var swiperH = (winWid * imgh) / imgw; //等比设置swiper的高度。 即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度  ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
      if (parseInt(swiperH) > this.data.LastHeight) {
        this.setData({
          Height: swiperH, //设置高度
        });
        this.data.LastHeight = parseInt(swiperH);
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getBanner();
    this.buttonGroup()
    let address_point = wx.getStorageSync("address-point");
    if (this.data.options.cityId) { //从选择城市页进入
      wx.setStorageSync('meituan_city_id', this.data.options.cityId)
      this.setData({
        city_name: this.data.options.city
      });
      if(address_point){
        this.data.point.lng = address_point.point.lng;
        this.data.point.lat = address_point.point.lat;
      }
      this.data.city_id = this.data.options.cityId;
      this.getCategory();
    } else if (address_point) {
      let city_name = address_point.city
      this.setData({
        city_name
      });
      this.data.point.lng = address_point.point.lng;
      this.data.point.lat = address_point.point.lat;
      this.get_city_id(city_name);
    } else {
      this.getLocationInfo();
    }
  },
  getLocationInfo() {
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        console.log(mapdata, "mapdata====")
        let city_name = mapdata.address_component.city || '';
        this.setData({
          city_name
        });
        this.data.point.lng = e.lng;
        this.data.point.lat = e.lat;
        this.get_city_id(city_name);
      });
    } catch (e) {
      console.log(e, "e============");
    }
  },

  buttonGroup() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.meituan-group-buy.frontend.index.button-group'),
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        let button_group = this.chunk(data, 10);
        this.setData({
          button_group
        })
      }
    })
  },
  getBanner() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.meituan-group-buy.frontend.index.rotation'),
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        this.setData({
          CarouseList: data
        })

        this.imgHeight();
      }
    })
  },
  getCategory() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.meituan-group-buy.frontend.good.category'),
      data: {
        city_id: this.data.city_id
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        this.setData({
          category_list: data
        });
        this.data.cate_id = data[0].id;
        this.getChildrenCategory()
      }
    })
  },
  getChildrenCategory() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.meituan-group-buy.frontend.good.category'),
      data: {
        city_id: this.data.city_id,
        first_cate_id: this.data.cate_id
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result !== 1) {
          return app.tips(msg);
        }
        this.setData({
          category_list_2: data
        });
        this.data.second_cate_id = data[this.data.second_category_index].id;
        this.getData();
      }
    })
  },
  getData(page = 1) {
    let json = {
      page,
      first_cate_id: this.data.cate_id,
      second_cate_id: this.data.second_cate_id,
      geo_info: {
        cityId: this.data.city_id
      }
    }

    if (this.data.point) {
      json.geo_info.lat = this.data.point.lat;
      json.geo_info.lng = this.data.point.lng;
    }
    app._postNetWork({
      url: app.getNetAddresss('plugin.meituan-group-buy.frontend.good.good'),
      data: json,
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result) {
          if (data.current_page == 1) {
            this.setData({
              list: data.records
            })
          } else if (data.current_page > 1) {
            this.data.list = this.data.list.concat(data.records)
            this.setData({
              list: this.data.list
            })
          }
          this.data.page = data.current_page;
          this.data.last_page = data.last_page;

        } else {
          app.tips(msg);
        }
      }
    })


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.page >= this.data.last_page) {
      return;
    }
    let page = this.data.page + 1;
    this.getData(page);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})